function getFilename(headerStr) {
  const reg = /filename\*?=([^;]*);?$/i;
  const match = reg.exec(headerStr);
  return match ? decodeURIComponent(match[1]) : Date.now();
}

function getHeaderKeyInsensive(header, key) {
  const lower = s => `${s}`.toLowerCase();
  const caseInsensiveHeader = Object.keys(header).reduce(
    (o, k) => ({ ...o, [lower(k)]: header[k] }),
    {}
  );
  return caseInsensiveHeader[lower(key)];
}

function exportApiData(api) {
  async function exportData(...rest) {
    const response = await api(...rest);
    const { data, headers } = response;
    const blob = new Blob([data]);
    const href = URL.createObjectURL(blob);
    const $anchor = document.createElement('a');
    const filename = getFilename(
      getHeaderKeyInsensive(headers, 'Content-Disposition')
    );

    $anchor.href = href;
    $anchor.target = '_blank';
    $anchor.download = filename;
    document.body.appendChild($anchor);
    $anchor.click();
    $anchor.remove();
  }
  return exportData;
}

export default {
  install(vue) {
    vue.prototype.$exportApiData = exportApiData;
  }
};
